package com.ceiec.trace.logback;

import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.encoder.Encoder;
import com.alibaba.fastjson.JSON;
import com.ceiec.trace.constant.ClientConstants;
import com.ceiec.trace.filter.RequestHolder;
import com.ceiec.trace.task.LogEventRunable;
import com.ceiec.trace.vo.LoggingEvent;
import com.ceiec.trace.vo.CurrentRequestMetaData;

/**
 * desc:
 *
 * @author : caokunliang
 * creat_date: 2018/9/11 0011
 * creat_time: 17:26
 **/
public class LogAggregatorAppender<E> extends UnsynchronizedAppenderBase<E> {
    protected Encoder<E> encoder;

    public void setEncoder(Encoder<E> encoder) {
        this.encoder = encoder;
    }


    @Override
    protected void append(E eventObject) {
        /**
         * 如果是程序启动时的日志，而不是一次request触发的日志，那么启动时的主线程是获取不到RequestMetaData的
         */
        CurrentRequestMetaData data = RequestHolder.get();
        if (data == null) {
            return;
        }

        //格式化日志内容
        String logContent = null;
        if (encoder instanceof LogAggregatorEncoder){
            LogAggregatorEncoder aggregatorEncoder = (LogAggregatorEncoder) this.encoder;
            logContent = aggregatorEncoder.encode2Str(eventObject);
        }

        /**
         * 构造日志请求vo
         */
        LoggingEvent event = new LoggingEvent();
        event.setDestIp(data.getDestHost());
        event.setTraceId(data.getTraceId());
        event.setAppName(data.getDestAppName());
        event.setLogContent(logContent);
        event.setTimestamp(System.currentTimeMillis());
        event.setDestPort(data.getDestPort());

        //异步发送到日志收集服务器
        ClientConstants.executorService.submit(new LogEventRunable("/" +  "processLogEvent.do", JSON.toJSONString(event)));
    }

    @Override
    public void start() {
        super.start();
    }
}
